package com.thinkfit.jy.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.common.lib.activity.BaseActivity;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.common.lib.utils.LogUtil;
import com.jakewharton.rxbinding3.widget.RxTextView;
import com.tencent.mm.opensdk.diffdev.DiffDevOAuthFactory;
import com.tencent.mm.opensdk.diffdev.IDiffDevOAuth;
import com.tencent.mm.opensdk.diffdev.OAuthErrCode;
import com.tencent.mm.opensdk.diffdev.OAuthListener;
import com.thinkfit.jy.R;
import com.thinkfit.jy.contract.LoginContract;
import com.thinkfit.jy.dialog.KeyboardPopupWindow;
import com.thinkfit.jy.presenter.LoginPresenter;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.ThemeUtils;
import com.thinkfit.jy.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View, OAuthListener {

    private Disposable mDisposableCountDown;
    private IDiffDevOAuth mOauth;
    private Bitmap mQRBmp;
    private boolean mIsGetCode;
    ConstraintLayout clMain;
    TextView tvArea, tvLanguage, tvUnit;
    private int mCurrentStyle;

    @Override
    protected int getLayoutId() {
//        mCurrentStyle = DataManager.Companion.getInstance().getMainStyle();
//        return mCurrentStyle == 3 ?
//                R.layout.activity_login_xm :
        return    R.layout.activity_login;
    }

    @Override
    protected void onCreated(@Nullable Bundle savedInstanceState) {
//        WindowManager.LayoutParams params = getWindow().getAttributes();
//        params.gravity = Gravity.LEFT | Gravity.TOP;
//        getWindow().setAttributes(params);
//        getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        if (mCurrentStyle == 3) {
            Bitmap bmp = (Bitmap) DataManager.Companion.getInstance().getObject();
            Bitmap newBmp = Bitmap.createBitmap(bmp, 0, 0, BaseUtils.StaticParams.dp2px(this, 320), getDisplayMetrics().heightPixels);
            setBackground(R.id.rootView, newBmp);
        }
        clMain = findViewById(R.id.cl_main);

        tvArea = findViewById(R.id.tv_area);
        tvLanguage = findViewById(R.id.tv_language);
        tvUnit = findViewById(R.id.tv_unit);

        setViewsOnClickListener(R.id.etPhone,R.id.etVerificationCode,R.id.tvWechat, R.id.tvPhoneLogin, R.id.tvGetCode, R.id.tvLogin,R.id.ll_sport_back);
        initInputListener();
        mOauth = DiffDevOAuthFactory.getDiffDevOAuth();
        mIsGetCode = false;
        getPresenter().getWXLoginQRCode();
        Utils.initRegion(tvArea, tvLanguage,tvUnit);
    }

    @Override
    protected void onResume() {
        super.onResume();
        SportsStatusBarViewUtils.getInstance().isMain(false);
        clMain.setBackgroundResource(ThemeUtils.getInstance().getMainTheme());
    }

    @Override
    protected void onStop() {
        super.onStop();
        System.out.println("ddddddddddddddddddddddd   LoginActivity ");
        DeviceTypeUtils.showBackButton(getApplicationContext());
    }

    @NonNull
    @Override
    protected LoginContract.Presenter onCreatePresenter() {
        return new LoginPresenter(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.etPhone:
                new KeyboardPopupWindow(this, (TextView) v).show(this);
                break;
            case R.id.etVerificationCode:
                new KeyboardPopupWindow(this, (TextView) v).show(this);
                break;
            case R.id.ll_sport_back:
                finish();
                break;
            case R.id.tvWechat:
                setText(R.id.tvType, R.string.app_wechat_login);
                setViewGone(R.id.llPhoneLogin, R.id.tvWechat);
                setViewVisible(R.id.llWechatLogin, R.id.tvPhoneLogin);
                if (mQRBmp == null) {
                    getPresenter().getWXLoginQRCode();
                }
                break;
            case R.id.tvPhoneLogin:
                setText(R.id.tvType, R.string.app_phone_register_or_login);
                setViewVisible(R.id.llPhoneLogin, R.id.tvWechat);
                setViewVisible(R.id.llWechatLogin, R.id.tvPhoneLogin);
                break;
            case R.id.tvGetCode:
                String phone = getTextById(R.id.etPhone);
                if (TextUtils.isEmpty(phone)) {
                    showToast(R.string.app_input_phone);
                    return;
                }
                getPresenter().sendCode(phone);
                v.setEnabled(false);
                startTimer();
                break;
            case R.id.tvLogin:
                phone = getTextById(R.id.etPhone);
                String code = getTextById(R.id.etVerificationCode);
                getPresenter().telLogin(phone, code);
                break;
        }
    }

    @Override
    public void sendCodeSuccess() {

    }

    @Override
    public void loginSuccess() {
        if (isFinish()) {
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put(EventBusEvent.LOGIN_SUCCESS,0);
        EventBus.getDefault().post(map);
        finish();
    }

    @Override
    public void getWXTicketSuccess(String ticket) {
        StringBuilder sb = new StringBuilder();// 定义变长字符串
        Random random = new Random();
        // 随机生成数字，并添加到字符串
        for (int i = 0; i < 8; i++) {
            sb.append(random.nextInt(10));
        }
        String nonceStr = sb.toString();
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String str = String.format("appid=%s&noncestr=%s&sdk_ticket=%s&timestamp=%s", Constants.WeChatAppID,
                nonceStr, ticket, timeStamp);
        LogUtil.LogE(str);
        String sha = BaseUtils.StaticParams.getSHA(str);
        mOauth.auth(Constants.WeChatAppID, "snsapi_userinfo", nonceStr, timeStamp, sha, this);
    }


    private void initInputListener() {
        final TextView tvLogin = findViewById(R.id.tvLogin);
        tvLogin.setEnabled(false);
        final TextView etPhone = findViewById(R.id.etPhone);
        final TextView etVerificationCode = findViewById(R.id.etVerificationCode);
        Observable.combineLatest(RxTextView.textChanges(etPhone).skip(1),
                RxTextView.textChanges(etVerificationCode).skip(1),
                (charSequence, charSequence2) -> !TextUtils.isEmpty(etPhone.getText().toString().trim()) &&
                        !TextUtils.isEmpty(etVerificationCode.getText().toString().trim())).subscribe(aBoolean -> {
            //不会判断输入的字节长度，有内容就能点击登录
            if (aBoolean && mIsGetCode) {
                tvLogin.setBackgroundResource(R.drawable.shape_gradient_d0b085_a87c42_0_30);
//                tvLogin.setBackgroundResource(mCurrentStyle == 3 ? R.drawable.shape_2bffffff_5 : R.drawable.shape_ffffff_5);
//                tvLogin.setTextColor(ContextCompat.getColor(LoginActivity.this,
//                        com.common.lib.R.color.color_21_20_20));
                tvLogin.setEnabled(true);
            } else {
                tvLogin.setBackgroundResource(
                        R.drawable.shape_gradient_60d0b085_60a87c42_0_30);
//                tvLogin.setTextColor(ContextCompat.getColor(this, com.common.lib.R.color.color_2b_fe_fe_fe));
                tvLogin.setEnabled(false);
            }
        });
//        etVerificationCode.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                System.out.println("dddddddddddddddddddddd  mIsGetCode : "+mIsGetCode);
//                //能判断验证码的字节长度
//                if(s.toString().length() >= 4 && mIsGetCode){
//                    tvLogin.setBackgroundResource(R.drawable.shape_ffffff_5);
//                    tvLogin.setBackgroundResource(mCurrentStyle == 3 ? R.drawable.shape_2bffffff_5 : R.drawable.shape_ffffff_5);
//                    tvLogin.setTextColor(ContextCompat.getColor(LoginActivity.this,
//                            com.common.lib.R.color.color_21_20_20));
//                    tvLogin.setEnabled(true);
//                } else {
//                    tvLogin.setBackgroundResource(
//                            R.drawable.shape_2bffffff_5);
//                    tvLogin.setTextColor(ContextCompat.getColor(LoginActivity.this, com.common.lib.R.color.color_2b_fe_fe_fe));
//                    tvLogin.setEnabled(false);
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });
        final TextView tvGetCode = findViewById(R.id.tvGetCode);
//        etPhone.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if (s.toString().length() == 11) {
//                    tvGetCode.setEnabled(true);
////                    tvGetCode.setBackgroundResource(mCurrentStyle == 3 ? R.drawable.shape_2bffffff_5 : R.drawable.shape_ffffff_5);
////                    tvGetCode.setTextColor(ContextCompat.getColor(LoginActivity.this,
////                            com.common.lib.R.color.text_color_9));
//                } else {
//                    tvGetCode.setEnabled(false);
////                    tvGetCode.setBackgroundResource(mCurrentStyle == 3 ? R.drawable.shape_2bffffff_5 :
////                            R.drawable.shape_3f3d3f_4);
////                    tvGetCode.setTextColor(ContextCompat.getColor(LoginActivity.this, com.common.lib.R.color.color_2b_fe_fe_fe));
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//
//            }
//        });
    }

    private void startTimer() {
        if (mDisposableCountDown != null) {
            mDisposableCountDown.dispose();
        }
        mDisposableCountDown = Observable.intervalRange(1, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        TextView tv = findViewById(R.id.tvGetCode);
                        if (aLong == 60) {
                            mIsGetCode = false;
                            tv.setText(getString(R.string.app_resend));
                            tv.setEnabled(true);
//                            tv.setBackgroundResource(mCurrentStyle == 3 ? R.drawable.shape_2bffffff_5 : R.drawable.shape_ffffff_4);
//                            tv.setTextColor(ContextCompat.getColor(LoginActivity.this,
//                                    mCurrentStyle == 3 ? com.common.lib.R.color.text_color_1 :
//                                            com.common.lib.R.color.text_color_9));
                            if (mDisposableCountDown != null) {
                                mDisposableCountDown.dispose();
                            }
                        } else {
                            mIsGetCode = true;
                            tv.setText(getString(R.string.app_xxx_second_get, String.valueOf(60 - aLong)));
                            tv.setEnabled(false);
//                            tv.setBackgroundResource(mCurrentStyle == 3 ? R.drawable.shape_2bffffff_5 :
//                                    R.drawable.shape_3f3d3f_4);
//                            tv.setTextColor(ContextCompat.getColor(LoginActivity.this, com.common.lib.R.color.color_2b_fe_fe_fe));
                        }
                    }
                });
    }

    public void onDestroy() {
        super.onDestroy();
        if (mDisposableCountDown != null) {
            mDisposableCountDown.dispose();
        }
        LogUtil.LogE("onDestroy");
        if (mOauth != null) {
            mOauth.removeAllListeners();
            mOauth.stopAuth();
            mOauth.detach();
        }
        if (mQRBmp != null && !mQRBmp.isRecycled()) {
            mQRBmp.recycle();
            mQRBmp = null;
        }
    }

    @Override
    public void onAuthGotQrcode(String s, byte[] bytes) {
        LogUtil.LogE("onAuthGotQrcode: " + s + ", " + bytes);
        mQRBmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        ((ImageView) findViewById(R.id.ivQrCode)).setImageBitmap(mQRBmp);
    }

    @Override
    public void onQrcodeScanned() {
        LogUtil.LogE("onQrcodeScanned");
    }

    @Override
    public void onAuthFinish(OAuthErrCode oAuthErrCode, String authCode) {
        LogUtil.LogE("onAuthFinish authCode:" + authCode);
        if (!TextUtils.isEmpty(authCode)) {
            getPresenter().scanQrCodeLogin(authCode);
        }
    }
}